package com.cdxy.aspect;

import com.cdxy.enums.BizErrorEnum;
import com.cdxy.enums.redis.RedisCacheGroupEnum;
import com.cdxy.model.dto.base.exception.BusinessException;
import com.cdxy.model.dto.base.redis.RedisCacheManager;
import com.cdxy.model.dto.resp.UserInfoResp;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.ProtocolException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * @Author: tangy
 * @Date: 2020/3/7 18:06
 */
@Aspect
@Component
@SuppressWarnings({"unused"})
@Slf4j
public class ForceLoginAspect {

    public static final String TOKEN_KEY = "Authorization";

    @Autowired
    private RedisCacheManager redisCacheManager;

    @Value("${auth.ax-user.private-key}")
    private String privateKey;

    @Value("${auth.ax-user.public-key}")
    private String publicKey;


    @Pointcut("@annotation(com.cdxy.aop.ForceLogin)")
    public void annotationPointcut() {
    }

    @Before("annotationPointcut()")
    public void beforePointcut(JoinPoint joinPoint) {


        // 此处进入到方法前  可以实现一些业务逻辑
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String authorization = attributes.getRequest().getHeader("Authorization");
        UserInfoResp userInfoResp = (UserInfoResp) redisCacheManager.get(RedisCacheGroupEnum.LOGIN_SUCCESS_TOKEN, authorization);
        if (userInfoResp == null) {
            throw new BusinessException(BizErrorEnum.LOGIN_NO_TOKEN);
        }
    }
}
